package ar.edu.uba.fi.jmit.monitorengine.backend.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.xml.sax.SAXException;

import ar.edu.uba.fi.jmit.monitorengine.Constants;
import ar.edu.uba.fi.jmit.monitorengine.backend.client.JMitFileService;
import ar.edu.uba.fi.jmit.monitorengine.backend.shared.dto.JMitFileDTO;
import ar.edu.uba.fi.jmit.monitorengine.parser.XMLDeleteFileParser;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class JMitFileServiceImpl extends RemoteServiceServlet implements JMitFileService {

	private static final long serialVersionUID = -266282693690593351L;

	@Override
	public void deleteFile(String fileName) {
		String pathToFile = Constants.getConfigurationsDirectory() + "/" + fileName;
		
		try {
			XMLDeleteFileParser.parse(pathToFile);
		} catch (SAXException e) {
			throw new RuntimeException("Cannot delete the file, the XMLParser found an error");
		} catch (IOException e) {
			throw new RuntimeException("Cannot delete the file, incorrect path");
		}
		File file = new File(pathToFile);
		if (!file.delete())
			throw new RuntimeException("Cannot delete the file, probably the file is locked by the OS");

	}

	@Override
	public List<JMitFileDTO> getLoadedConfigurationFiles() {
		
		List<JMitFileDTO> jMitFiles = new ArrayList<JMitFileDTO>();
		
		String configDir = Constants.getConfigurationsDirectory();
		File dir = new File(configDir);
		String[] files = dir.list();
		if (files != null) {
			for (String file : files) {
				int length = file.length();
				if (length > 9 && file.substring(length - 3, length).equals("xml") && file.substring(length - 8, length - 4).equals("jmit")){
					JMitFileDTO dto = new JMitFileDTO();
					dto.setName(file);
					dto.setPath(configDir);
					
					jMitFiles.add(dto);
				}
			}
		}
		return jMitFiles;
	}

	@Override
	public String getFileText(String fileName) throws IOException {
		FileReader reader = new FileReader(new File(Constants.getConfigurationsDirectory() + "/" + fileName));
		BufferedReader buffReader = new BufferedReader(reader);
		StringBuffer buff = new StringBuffer();
		String line = buffReader.readLine();
		while(line != null) {
			buff.append(line + "\n");
			line = buffReader.readLine();
		}
		buffReader.close();
		reader.close();
		return buff.toString();
	}
}
